
#import "LoginViewController.h"

@implementation LoginViewController

//
// user name
//
@synthesize userName														= _userName;

//
// password
//
@synthesize password														= _password;

//
// captcha
//
@synthesize captcha															= _captcha;

//
// captcha image data
//
@synthesize captchaImageData												= _captchaImageData;

//
// session id
//
@synthesize sessionId														= _sessionId;

//
// callback
//
@synthesize callback														= _callback;

//
// init
//
- (id)init
{
	//
	// call super
	//
	self																	= [super initWithStyle:UITableViewStyleGrouped];
	if(!self)
		return nil;
	
	//
	// setup variables
	//
	self.userName															= @"";
	self.password															= @"";
	self.captcha															= @"";
	self.title																= NSLocalizedStringFromTable(@"Login", @"LoginViewController", nil);
	self.navigationItem.rightBarButtonItem									= [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshLoginForm:)] autorelease];
	self.navigationItem.leftBarButtonItem									= [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(startLogin:)] autorelease];
	
	return self;
}

//
// dealloc
//
- (void)dealloc
{
	self.userName															= nil;
	self.password															= nil;
	self.captcha															= nil;
	self.captchaImageData													= nil;
	self.sessionId															= nil;
	self.callback															= nil;
	
	[super dealloc];
}

//
// refresh login form
//
- (void)refreshLoginForm:(id)sender
{
	NexusClient* client														= [NexusClient sharedClient];
	
	//
	// get captcha image finished
	//
	id getCaptchaImageFinished = [[^void(NexusHttpRequest* httpRequest)
	{
		[ActivityView removeView];
		if(!httpRequest.error && httpRequest.response.statusCode == 200)
		{
			self.captchaImageData											= httpRequest.dataBuffer;
			self.sessionId													= httpRequest.cookiePHPSessionId;
			[self.tableView reloadData];
		}
		else
		{
			NSString* message												= [httpRequest errorDescription];
			NSString* title													= NSLocalizedStringFromTable(@"Get Captcha Image Failed", @"LoginViewController", nil);
			[UIAlertView alertViewWithTitle:title message:message cancel:NSLocalizedString(@"OK", nil)];
		}		
	} copy] autorelease];
	
	//
	// get login form finished
	//
	id getLoginFormFinished = ^void(GetLoginFormRequest* httpRequest)
	{
		if(!httpRequest.error && httpRequest.response.statusCode == 200)
		{
			[[ActivityView currentView] updateText:NSLocalizedStringFromTable(@"Getting Captcha", @"LoginViewController", nil)];
			[client getCaptchaImage:httpRequest.captchaAddress callback:getCaptchaImageFinished];
		}
		else
		{
			[ActivityView removeView];
			NSString* message												= [httpRequest errorDescription];
			NSString* title													= NSLocalizedStringFromTable(@"Get Login Form Failed", @"LoginViewController", nil);
			[UIAlertView alertViewWithTitle:title message:message cancel:NSLocalizedString(@"OK", nil)];
		}
	};
	
	//
	// get login form
	//
	[ActivityView showActivityView:NSLocalizedStringFromTable(@"Getting Login Form", @"LoginViewController", nil) networking:YES withView:self.navigationController.view];
	[client getLoginFormWithCallback:getLoginFormFinished];
}

//
// did show
//
- (void)viewDidAppear:(BOOL)animated
{
	[super viewDidAppear:animated];
	[self refreshLoginForm:nil];
}

//
// get section count
//
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
	return 1;
}

//
// get row count
//
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
	return 4;
}

//
// get title
//
- (NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section
{
	return NSLocalizedStringFromTable(@"Login Form", @"LoginViewController", nil);
}

//
// get cell
//
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
	if(indexPath.row == 2)
	{
		static NSString* resueIdentifier									= @"captchaCell";
		UITableViewCell* theCell											= [tableView dequeueReusableCellWithIdentifier:resueIdentifier];
		if(!theCell)
			theCell															= [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:resueIdentifier] autorelease];
		
		UIImageView* captchaImageView										= [[[UIImageView alloc] initWithImage:[UIImage imageWithData:self.captchaImageData scale:2]] autorelease];
		theCell.accessoryView												= captchaImageView;
		theCell.selectionStyle												= UITableViewCellSelectionStyleNone;
		theCell.accessoryType												= UITableViewCellAccessoryNone;
		theCell.textLabel.text												= NSLocalizedStringFromTable(@"Image", @"LoginViewController", nil);
		return theCell;
	}
	UITableViewCell* theCell												= [tableView dequeueReusableCellWithIdentifier:@"v1"];
	if(!theCell)
		theCell																= [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"v1"] autorelease];
	
	UITextField* textField													= [[[UITextField alloc] initWithFrame:CGRectMake(0, 0, 140, 21)] autorelease];
	switch(indexPath.row)
	{
		//
		// user name
		//
	case 0:
		theCell.textLabel.text												= NSLocalizedStringFromTable(@"E-Mail", @"LoginViewController", nil);
		textField.placeholder												= @"example@apple.com";
		textField.text														= self.userName;
		textField.tag														= 0;
		textField.keyboardType												= UIKeyboardTypeEmailAddress;
		textField.returnKeyType												= UIReturnKeyNext;
		break;
		
		//
		// password
		//
	case 1:
		theCell.textLabel.text												= NSLocalizedStringFromTable(@"Password", @"LoginViewController", nil);
		textField.placeholder												= @"";
		textField.text														= self.password;
		textField.tag														= 1;
		textField.keyboardType												= UIKeyboardTypeASCIICapable;
		textField.returnKeyType												= UIReturnKeyNext;
		textField.secureTextEntry											= YES;
		break;
		
		//
		// captcha
		//
	case 3:
		theCell.textLabel.text												= NSLocalizedStringFromTable(@"Captcha", @"LoginViewController", nil);
		textField.placeholder												= @"";
		textField.text														= self.captcha;
		textField.tag														= 3;
		textField.keyboardType												= UIKeyboardTypeASCIICapable;
		textField.returnKeyType												= UIReturnKeyDone;
		break;
	}
	
	textField.adjustsFontSizeToFitWidth										= YES;
	textField.autocorrectionType											= UITextAutocorrectionTypeNo;
	textField.autocapitalizationType										= UITextAutocapitalizationTypeNone;
	textField.clearButtonMode												= UITextFieldViewModeWhileEditing;
	textField.delegate														= self;
	theCell.accessoryView													= textField;
	theCell.selectionStyle													= UITableViewCellSelectionStyleNone;
	theCell.accessoryType													= UITableViewCellAccessoryNone;
	
	return theCell;
}

//
// select row
//
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
	if(indexPath.row != 2)
	{
		UITableViewCell* theCell											= [tableView cellForRowAtIndexPath:indexPath];
		[theCell.accessoryView becomeFirstResponder];
	}
}

//
// done
//
- (void)startLogin:(id)sender
{
	[self.tableView endEditing:YES];
	
	NSString* message														= nil;
	if(!self.userName.length)
		message																= NSLocalizedStringFromTable(@"Please input user name", @"LoginViewController", nil);
	else if(!self.password.length)
		message																= NSLocalizedStringFromTable(@"Please input password", @"LoginViewController", nil);
	else if(!self.captcha.length)
		message																= NSLocalizedStringFromTable(@"Please input captcha", @"LoginViewController", nil);
	
	if(message)
		[UIAlertView alertViewWithTitle:NSLocalizedString(@"Error", nil) message:message cancel:NSLocalizedString(@"OK", nil)];
	else if(self.callback)
		self.callback(self.userName, self.password, self.captcha, self.sessionId);
}

//
// end editing
//
- (void)textFieldDidEndEditing:(UITextField*)textField
{
	switch(textField.tag)
	{
	case 0:
		self.userName														= textField.text;
		break;
			
	case 1:
		self.password														= textField.text;
		break;
		
	case 3:
		self.captcha														= textField.text;
		break;
	}
}

//
// return
//
- (BOOL)textFieldShouldReturn:(UITextField*)textField
{
	switch(textField.tag)
	{
	case 0:
		[[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]].accessoryView becomeFirstResponder];
		break;
			
	case 1:
		[[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]].accessoryView becomeFirstResponder];
		break;
			
	case 3:
		[self startLogin:textField];
		break;
	}
	return YES;
}

@end
